package com.mars.push.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mars.push.core.constant.Constant;
import com.mars.push.core.httpclient.HttpClientService;
import com.mars.push.core.request.PushRequest;
import com.mars.push.core.response.SendResponse;
import com.mars.push.core.service.PushService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wq
 * @version 1.0
 * @date 2021/03/05 14:34
 */
@Service
@Slf4j
public class OppoPushServiceImpl implements PushService {

    @Resource
    private HttpClientService httpClientService;

    @Value("${push.oppo.appKey}")
    private String appKey;

    @Value("${push.oppo.masterSecret}")
    private String masterSecret;


    @Override
    public boolean singlePush(PushRequest req) throws Exception {
        String accessToken = getAccessToken();
        Map<String, Object> map = new HashMap<>();
        map.put("auth_token", accessToken);
        JSONObject jsonData = new JSONObject();
        jsonData.put("target_type", 2);
        jsonData.put("target_value", req.getRegisterId());

        //封装消息内容
        JSONObject notification = new JSONObject();
        notification.put("title", req.getTitle());
        notification.put("style", 1);
        notification.put("click_action_type", 0);
        notification.put("off_line", true);
        notification.put("content", req.getContent());
        jsonData.put("notification", notification);
        map.put("message", jsonData);
        SendResponse sendResponse = httpClientService.doPost(Constant.OPPO_SERVER_URL + Constant.OPPO_PUSH_URL, map);
        return JSONObject.parseObject(sendResponse.getMsg()).getInteger("code").equals(Constant.ZERO);
    }

    @Override
    public String getAccessToken() throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("app_key", appKey);
        long time = System.currentTimeMillis();
        String encodeData = appKey + time + masterSecret;
        map.put("sign", getSha256(encodeData));
        map.put("timestamp", time);
        SendResponse sendResponse = httpClientService.doPost(Constant.OPPO_SERVER_URL + Constant.OPPO_TOKEN_URL, map);
        String msg = sendResponse.getMsg();
        if (Constant.ZERO.equals(JSONObject.parseObject(msg).getInteger("code"))) {
            String data = JSONObject.parseObject(msg).getString("data");
            return JSONObject.parseObject(data).getString("auth_token");
        }
        return null;
    }


    /**
     * 获取sha256
     *
     * @param data data
     * @return String
     */
    public static String getSha256(String data) {
        MessageDigest messageDigest;
        String encodestr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(data.getBytes(StandardCharsets.UTF_8));
            encodestr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return encodestr;
    }

    private static String byte2Hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        String temp = null;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                sb.append("0");
            }
            sb.append(temp);
        }
        return sb.toString();
    }

}
